package com.maint.m

import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.WindowInsets
import android.view.WindowInsetsController
import android.widget.FrameLayout
import android.widget.LinearLayout
import android.widget.TextView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import com.google.gson.Gson
// 移除直接引用
import com.maint.m.databinding.ActivityMainBinding
import com.rokid.security.phone.sdk.api.PSecuritySDK
import com.rokid.security.phone.sdk.base.data.callback.IResultCallback
import com.maint.m.data.GlobalData
import com.rokid.security.phone.sdk.base.data.EnvType
import kotlinx.coroutines.launch
import pub.devrel.easypermissions.EasyPermissions

import com.maint.m.GlassConnectionActivity
import com.maint.m.utils.XunfeiTtsUtil


open class BaseActivity : AppCompatActivity(), EasyPermissions.PermissionCallbacks {
    private lateinit var binding: ActivityMainBinding
    
    // 提供简洁的方式访问PSecuritySDK消息服务
    protected val mAbsSecurityMessageService by lazy {
        PSecuritySDK.getMessageService()
    }

    companion object{
        val mEnvType = EnvType.PUBLIC_TEST
        lateinit var instance: BaseActivity
    }

    private val TAG = "BaseActivity::"

    var isWifiConnect = false
    var isBtConnect = false
    var mGson = Gson()

    protected var toolbar: Toolbar? = null
        private set

    private val permission : Array<String> = run {
        val list = arrayListOf<String>()

        list.add(Manifest.permission.CAMERA) // 相机权限
        list.add(Manifest.permission.RECORD_AUDIO) // 录音权限

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            list.add(Manifest.permission.BLUETOOTH_SCAN) // 蓝牙权限 扫描权限
            list.add(Manifest.permission.BLUETOOTH_CONNECT) // 蓝牙权限 连接权限
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            list.add(Manifest.permission.NEARBY_WIFI_DEVICES) // WiFi P2P 权限
        } else {
            list.add(Manifest.permission.ACCESS_FINE_LOCATION) // 定位权限
            list.add(Manifest.permission.ACCESS_COARSE_LOCATION) // 模糊定位权限
        }
        list.add(Manifest.permission.ACCESS_FINE_LOCATION) // 定位权限

        list.toTypedArray()
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()

        binding = ActivityMainBinding.inflate(layoutInflater)

        setContentView(binding.root)

        checkPermissionList()

        // 科大讯飞初始化
        val appId = "9cd2c76b"
        com.iflytek.cloud.SpeechUtility.createUtility(this, "appid=$appId")

        // 初始化 TTS 工具类
        XunfeiTtsUtil.init(this) { success, errorMsg ->
            if (success) {
                android.util.Log.i("BaseActivity", "科大讯飞TTS引擎初始化成功")
            } else {
                android.util.Log.e("BaseActivity", "科大讯飞TTS引擎初始化失败: $errorMsg")
            }
        }

    }


    private fun checkPermissionList(): Boolean {
        val hasPermissions = EasyPermissions.hasPermissions(this, *permission)
        // val p2 = checkAndroid11StoragePermission()
        if (!hasPermissions) {
            EasyPermissions.requestPermissions(
                this, 
                "App需要申请相关权限",
                999, 
                *permission
            )
            return false
        }

        return true
    }

    fun checkAndroid11StoragePermission() : Boolean {
        // 目前只有警务网证书放在公共目录有这个需求，非警务网不看这个权限
        if (mEnvType != EnvType.ZJST){
            return true
        }
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            // Android 11及以上，检查是否有管理所有文件的权限
            if (Environment.isExternalStorageManager()) {
                true
            } else {
                false
            }
        } else {
            true
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int, permissions: Array<String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this)
    }

    override fun onPermissionsGranted(requestCode: Int, perms: MutableList<String>) {
    }

    override fun onPermissionsDenied(requestCode: Int, perms: MutableList<String>) {
        Log.e(TAG, "权限被拒绝：$perms")
    }



    @SuppressLint("SetTextI18n")
    private fun connectStatus(bt_success: Boolean,p2_success: Boolean){

        Log.i(TAG, "connectStatus: bt_success: $bt_success p2_success: $p2_success")


    }


    // WebSocket 消息处理器
    private val webSocketHandler = object : SimpleWebSocketHandler {
        override fun onMessageReceived(type: WebSocketMessageType, message: String) {
            // 基类默认实现，可以在子类中覆盖
            Log.d("BaseActivity", "收到WebSocket消息: $type, 内容: $message")
        }

        override fun onConnectionChanged(connected: Boolean) {
            // 基类默认实现，可以在子类中覆盖
            val status = if (connected) "已连接" else "未连接"
            Log.d("BaseActivity", "WebSocket连接状态: $status")
        }

        override fun onError(errorMsg: String) {
            // 基类默认实现，可以在子类中覆盖
            Log.e("BaseActivity", "WebSocket错误: $errorMsg")
        }
    }

    override fun onResume() {
        super.onResume()
        setFullScreen()

        // 使用封装的 WebSocketService
        val webSocketService = WebSocketService.getInstance()
        
        // 注册消息处理器
        webSocketService.registerHandler(webSocketHandler, this)
        
        // 自动连接（如果未连接）
        if (!webSocketService.isConnected()) {
            webSocketService.connect()
            Log.d("BaseActivity", "恢复活动，连接 WebSocket")
        }
    }

    override fun onPause() {
        super.onPause()
        // 可以在这里保持连接，不需要断开
    }

    override fun onDestroy() {
        super.onDestroy()
        // 页面销毁时注销处理器，但保持连接
        WebSocketService.getInstance().unregisterHandler(webSocketHandler)
    }

    /**
     * 发送 WebSocket 消息的便捷方法
     */
    protected fun sendWebSocketMessage(message: String, showToast: Boolean = false): Boolean {
        return WebSocketService.getInstance().sendMessage(message, showToast, this)
    }

    /**
     * 发送结构化 WebSocket 消息的便捷方法
     */
    protected fun sendStructuredWebSocketMessage(business: Int, data: Any? = null, showToast: Boolean = false): Boolean {
        return WebSocketService.getInstance().sendStructuredMessage(business, data, showToast, this)
    }

    private fun setFullScreen() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            val controller = window.insetsController
            if (controller != null) {
                controller.hide(WindowInsets.Type.statusBars())
                controller.hide(WindowInsets.Type.navigationBars())
                controller.systemBarsBehavior = WindowInsetsController.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
            }
        } else {
            @Suppress("DEPRECATION")
            window.decorView.systemUiVisibility = (
                    View.SYSTEM_UI_FLAG_FULLSCREEN
                            or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                            or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                            or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                            or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    )
        }
    }

    override fun setContentView(layoutResID: Int) {
        // 创建包装布局
        val rootLayout = LayoutInflater.from(this)
            .inflate(R.layout.base_activity, null) as LinearLayout

        // 将内容布局添加到FrameLayout中
        val contentFrame = rootLayout.findViewById<FrameLayout>(R.id.content_frame)
        LayoutInflater.from(this).inflate(layoutResID, contentFrame, true)

        super.setContentView(rootLayout)
        initToolbar()
    }

    private var toolbarTitle: TextView? = null

    private fun initToolbar() {
        // 直接从rootView查找自定义标题TextView，而不是通过Toolbar查找
        toolbarTitle = findViewById<TextView>(R.id.toolbar_title)
        
        // 隐藏系统默认的标题，因为我们使用自定义的TextView
        supportActionBar?.setDisplayShowTitleEnabled(false)
    }

    /**
     * 设置标题栏的标题文本
     */
    protected fun setToolbarTitle(title: String) {
        toolbarTitle?.let { it.text = title }
    }
}
